﻿#include"MessagePro.h"
#include<iostream>
#include<string>
#include"tools.h"
using namespace std;

MessagePro::MessagePro()
{
	flag = false;
	this->m_strServerip = "127.0.0.1";
	this->m_port = 8080;
}

MessagePro::MessagePro(CString m_strServerip, int m_port)
{
	flag = false;
	this->m_strServerip = m_strServerip;
	this->m_port = m_port;
}

MessagePro::~MessagePro()
{
	if (flag) {
		m_pSock->Close();
		delete m_pSock;
	}
}

bool MessagePro::Init()
{
	if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
	{
		cerr << "MFC failed to initialize!" << endl;
		return false;
	}
	AfxSocketInit();
	m_pSock = new CClientSocket();
	if (!m_pSock->Create())
	{
		cout << "创建套接字失败！" << endl;
		delete m_pSock;
		getchar();
		return false;
	}
	if (!m_pSock->Connect(m_strServerip, m_port))
	{
		cout << "连接服务器失败！" << endl;
		delete m_pSock;
		getchar();
		return false;
	}
	flag = true;
	cout << "连接服务器成功！" << endl;
	return true;
}

bool MessagePro::SendMsg(const char *buf)
{
	this->m_pSock->Send(buf, strlen(buf));
	return true;
}

bool MessagePro::SendMsg(string str)
{
	this->m_pSock->Send(str.c_str(), str.length());
	return true;
}

void  MessagePro::FormatMsg(string str)
{
	string placeholder = "-------";
	vector <string>vec = split(str, "\r\n");
	for (unsigned int i = 0; i < vec.size(); i++) {
		vector <string>vec_temp = split(vec[i], "|");
		for (unsigned int j = 0; j < vec_temp.size(); j++)
			cout << placeholder;
		cout << endl;
		cout << vec[i] << endl;
	}

}

bool MessagePro::ReceiveLoginInfo(string &info) {
	char pData[1024] = { 0 };
	if (m_pSock->Receive(pData, 1024, 0) != SOCKET_ERROR) {
		info = pData;
		cout << info << endl;
		if (info == "userName or password is not correct !") {
			return false;
		}
		else if (info == "Login successful !") {
			cout << "Welcome to the DBMS monitor." << endl;
			cout << "Type 'quit' or '\\q' for exiting." << endl;
			cout << "Type 'help' or '\\h' for help." << endl;
			cout << "Type 'use' for using another database." << endl;
			return true;
		}
	}
	return false;
}

bool MessagePro::ReceiveMsg()
{
	char pData[1024] = { 0 };
	if (m_pSock->Receive(pData, 1024, 0) != SOCKET_ERROR)
	{
		string temp = pData;
		string output, msg;
		bool isSelect = false;
		while (temp.substr(0, 1) == "1") {
			output = temp.substr(1, 1023);
			if (output.substr(0, 6) == "select") {
				isSelect = true;
				output = output.substr(7, 1017);
			}
			memset(pData, 0, 1024);
			m_pSock->Receive(pData, 1024, 0);
			temp = pData;
			msg += output;
		}

		///*
		output = temp.substr(1, 1023);
		if (output.substr(0, 6) == "select") {
			msg = output.substr(7, 1017);
		}
		else if (isSelect) {
			msg += output;
		}
		else {
			cout << output << endl;
			return true;
		}
		this->FormatMsg(msg);
		return true;
	}
	return false;
}

